import cloud from '@lafjs/cloud'
let dbName = "admin-roles"
const db = cloud.database();

export default async function (ctx: FunctionContext) {
  let dataJson = { ...ctx.body.data }
  switch (ctx.body.type) {
    case "list"://列表-分页
      delete dataJson.pageIndex
      delete dataJson.pageSize
      let query = cloud.utils.extractValidKeys(dataJson)
      let res = await cloud.nw.db.select({
        dbName,
        getCount: true,
        pageIndex: ctx.body.pageIndex,
        pageSize: ctx.body.pageSize,
        whereJson: query,
        sortArr: [{ "name": "sort", "type": "asc" }],
      });
      return cloud.utils.requestReturn({ data: res })
      break;
    case "query"://列表-不分页
      let { data } = await db.collection(dbName).get();
      return cloud.utils.requestReturn({ data })
      break;
    case "add"://新增
      dataJson._add_time = Date.now()
      await cloud.nw.db.add({
        dbName, dataJson, cancelAddTime: true
      });
      return cloud.utils.requestReturn({ data: "" })
      break;
    case "update"://编辑
      delete dataJson._id
      if (!dataJson._add_time) dataJson._add_time = Date.now()
      await cloud.nw.db.update({
        dbName, whereJson: { _id: ctx.body.data._id }, dataJson
      });
      return cloud.utils.requestReturn({ data: "" })
      break;
    case "delete"://删除
      delete dataJson._id
      await cloud.nw.db.del({
        dbName, whereJson: { _id: ctx.body.data._id }
      });
      return cloud.utils.requestReturn({ data: "" })
      break;
    default:
      break;
  }
}
